package ml.stayfool.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * Created by pactera on 2017/1/11.
 */
public class JsonUtil {
    private static final ObjectMapper MAPPER;

    private static Logger logger = LoggerFactory.getLogger(JsonUtil.class);

    static {
        MAPPER = new ObjectMapper();
    }

    public static <T> T fromJson(String json, Class<T> cls) {
        try {
            return MAPPER.readValue(json, cls);
        } catch (IOException e) {
            logger.error("read json to object failed", e);
        }
        return null;
    }

    public static String toJson(Object obj) {
        try {
            return MAPPER.writeValueAsString(obj);
        } catch (IOException e) {
            logger.error("write object to json failed", e);
        }
        return null;
    }
}
